﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using FMSpaceShooter.Screens;

namespace FMSpaceShooter.GameObjects
{
    class Negotiator : IDisposable
    {
        const int LockTime = 12;
        const int FireTime = 12;
        const int FireDelay = 150;
        GameplayScreen screen;
        HashSet<ObjectBase> enemiesList = new HashSet<ObjectBase>();
        TimeSpan? start = null;
        bool done = false;

        public bool IsFinished
        {
            get { return done; }
        }


        public Negotiator(GameplayScreen screen)
        {
            this.screen = screen;
        }

        public void Update(GameTime gameTime)
        {
            if (!done)
            {
                if (start == null)
                {
                    start = gameTime.TotalGameTime;
                }
                var enemies = screen.GOM.GameObjects.Where(go => !go.IsFriendly && !enemiesList.Contains(go))
                    .OrderBy(go => Vector2.Distance(go.Position, screen.GOM.PlayerOne.Position)).ToList();

                for (int i = 0; i < enemies.Count; i++)
                {
                    TimeSpan lockTime = (TimeSpan)start + TimeSpan.FromMilliseconds(enemiesList.Count * LockTime);
                    TimeSpan fireTime = (TimeSpan)start + TimeSpan.FromMilliseconds(enemiesList.Count * FireTime + FireDelay);
                    Javelin jav = new Javelin(screen, enemies[i],
                            screen.GOM.PlayerOne.Position,
                            lockTime, fireTime);

                    screen.GOM.AddToPlay(jav);
                    enemiesList.Add(enemies[i]);
                }
                if (enemies.Count == 0 && !screen.GOM.GameObjects.Where(go => go is Javelin).Any())
                {
                    done = true;
                }
            }
        }


        public void Dispose()
        {
        }
    }
}
